package com.midea.thread;

import java.util.concurrent.TimeUnit;

import static com.midea.exam.RotatePrint.lock;

/**
 * @Author: Mr.Wang
 * @Description:死锁分析命令
 * jps -l
 * jstack
 * @Date: Create in 14:00 2022/4/10
 */
public class DeadLockDemo {


    public static void main(String[] args) {
        String lockA = "lockA";
        String lockB = "lockB";
        new Thread(new HoldLockThread(lockA,lockB),"ThreadA").start();
        new Thread(new HoldLockThread(lockB,lockA),"ThreadB").start();
    }
}

class HoldLockThread implements Runnable {
    private String lockA;
    private String lockB;

    public HoldLockThread(String lockA, String lockB) {
        this.lockA = lockA;
        this.lockB = lockB;
    }

    @Override
    public void run() {
        synchronized(lockA) {
            System.out.println(String.format("%s自己持有%s，尝试持有%s",Thread.currentThread().getName(),lockA,lockB));

            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized(lockB) {
                System.out.println(String.format("%s同时持有%s，%s",Thread.currentThread().getName(),lockA,lockB));
            }
        }

    }
}
